import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
// import LanguageDetector from 'i18next-browser-languagedetector'
// import Backend from 'i18next-http-backend'
import dayjs from 'dayjs'
import 'dayjs/locale/zh'
import 'dayjs/locale/en'
import resource from '@/locales'

const LAN_BASE_STORE = 'APP_LANG_DATA'

export type LangType = 'en' | 'zh'

export const langOptions = {
  'zh': { label: 'English', value: 'zh' },
  'en': { label: '中文', value: 'en' }
}

const initDayjs = (lan: LangType) => {
  dayjs.locale(lan)
  i18n.services.formatter.add('DD/MM/YY', (value) => {
    return dayjs(value).format('DD/MM/YY')
  })

  i18n.services.formatter.add('YYYY-MM-DD', (value) => {
    return dayjs(value).format('YYYY-MM-DD')
  })
}

export const checkI18nStore = (): LangType | null => {
  const lang = localStorage.getItem(LAN_BASE_STORE) as LangType
  if (lang) {
    return lang
  }
  return null
}

export const initI18n = (baseLan: LangType = 'zh') => {
  const lan = checkI18nStore() || baseLan
  i18n
    .use(initReactI18next)
    // https://www.i18next.com/overview/configuration-options
    .init({
      debug: true,
      fallbackLng: lan,
      interpolation: {
        escapeValue: false,
      },
      resources: resource,
    })
  initDayjs(lan)
}

export const changeLan = (lan: LangType) => {
  i18n.changeLanguage(lan)
  dayjs.locale(lan)
  localStorage.setItem(LAN_BASE_STORE, lan)
} 
